const { createClient } = require("redis");
const { v4: uuidv4 } = require("uuid");
const config = require("../../config");

class Command {
    constructor(machineUuid) {
        if (config.redis.password) {
            this.redisUrl = `redis://:${config.redis.password}@${config.redis.host}:${config.redis.port}/${config.redis.db}`;
        } else {
            this.redisUrl = `redis://${config.redis.host}:${config.redis.port}/${config.redis.db}`;
        }
        this.machineUuid = machineUuid;
        this.commandUuid = uuidv4();
    }

    _createCommandType() {
        return "test";
    }

    _createCommandData() {
        return {};
    }

    async push() {
        const key = `command:${this.machineUuid}`;
        const value = {
            commandType: this._createCommandType(),
            commandUuid: this.commandUuid,
            commandData: this._createCommandData(),
            machineUuid: this.machineUuid,
        }
        const redisClient = createClient({ url: this.redisUrl });
        await redisClient.connect();
        await redisClient.rPush(key, JSON.stringify(value));
        await redisClient.disconnect();
    }

    async pop() {
        const redisClient = createClient({ url: this.redisUrl });
        redisClient.connect();
        const key = `command:${this.machineUuid}`;
        let value = await redisClient.lPop(key);
        redisClient.disconnect();
        return JSON.parse(value);
    }
}

module.exports = Command;